package com.abc.chatprj;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/login")
public class Loginservlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        Object obj = this.getServletContext().getAttribute("users");
        if(obj == null){
            List<String> list = new ArrayList<>();
            list.add(username);
            this.getServletContext().setAttribute("users",list);
            request.getSession().setAttribute("myself",username);
            response.sendRedirect("chat/main.jsp");
        }else{
            List<String> list = (List<String>) obj;
            if(list.contains(username)){
                request.setAttribute("errorinfo","该名称已被使用，请更换");
                request.getRequestDispatcher("index.jsp").forward(request, response);
            }else{
                list.add(username);
                this.getServletContext().setAttribute("users",list);
                request.getSession().setAttribute("myself",username);
                response.sendRedirect("chat/main.jsp");
            }
        }

    }

}
